package api.lock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZookeeperClient {

    private static final String CONNECT_STRING = "127.0.0.1:2181";

    private static int sessionTimeout = 5000;

    public static ZooKeeper getInstance() throws IOException, InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zookeeper = new ZooKeeper(CONNECT_STRING, sessionTimeout,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        if (event.getState() == Event.KeeperState.SyncConnected) {
                            countDownLatch.countDown();
                        }
                    }
                });

        countDownLatch.await();
        return zookeeper;
    }

    public static int getSessionTimeout() {
        return sessionTimeout;
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = ZookeeperClient.getInstance();
        System.out.println(zooKeeper);
    }
}
